// pages/register/register.js
import {
  apiList,
  ApiRootUrl
} from '../../config/index.js'
import Toast from '../../@vant/weapp/toast/toast';
import Dialog from '../../@vant/weapp/dialog/dialog';
import {
  IMG_PATH
} from '../../config/index.js'
import{
  request,login,isPhone,isName
} from "../../utils/util"
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    IMG_PATH: IMG_PATH,
    message:"会话已过期！请重新登录！",
    tishiShow:false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    username: '',
    phone: '',
    company: '请选择',
    identifycode: '',
    showcompany: false,
    columns: [],
    orgCode: '',
    code: "",
    name: "",
    type: "",
    canLogin:false,
    count:3,
    showUserList:false,
    userList:[],
    editusername:false,
    editidentity:false,
  },
  usernameInput(event) {
    console.log(event);
    this.setData({
      username: event.detail
    })
  },
  usernameBlur(event) {
    console.log(event);
    this.setData({
      username: event.detail.value
    })
  },
  identifycodeInput(event) {
    this.setData({
      identifycode: event.detail
    })
  },
  identifycodeBlur(event) {
    console.log(event);
    this.setData({
      identifycode: event.detail.value
    })
  },
  getPhoneNumber(e) {
    let self = this;
    let flag = true;
    wx.checkSession({
      success: function (res) {
        console.log('session_key未过期')
        //session_key未过期
        flag = true;
      },
      fail: function (res) {
        flag = false;
        self.setData({
          tishiShow: true
        })
      }
    })
    if (!flag) {
      return;
    }
    let openId = wx.getStorageSync("openId");
    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      let url = `${ApiRootUrl}/index/grantPhone`;
      let params = {
        iv: e.detail.iv,
        encryptedData: e.detail.encryptedData
      }
      Toast.loading({
        message: '加载中...',
        mask: true,
        duration: 0,
        forbidClick: true,
      });
      wx.request({
        url: url,
        method: 'GET',
        header: {
          'content-type': 'application/json; charset=utf-8',
          'cookie': wx.getStorageSync("sessionid")
        },
        params: params,
        data: params,
        success(res) {
          Toast.clear();
          if (res.data.code == 20000) {
            let phoneNumber = res.data.data;
            wx.setStorageSync("phoneNumber", phoneNumber);
            self.setData({
              phone: phoneNumber,
              getPhoneNumberFlag: false
            })
          } else if (res.data.code == 30000) {
            self.setData({
              tishiShow: true
            })
          } else {
            Toast({
              duration: 3000,
              forbidClick: true,
              type: 'fail',
              message: res.data.message,
              mask:true
            });
          }
        },
        fail(res) {
          Toast.clear();
          Toast({
            duration: 3000,
            forbidClick: true,
            type: 'fail',
            message: '网络已断开',
          });
        }
      })
    } else {
      Toast({
        duration: 3000,
        forbidClick: true,
        type: 'fail',
        message: '不授权将无法登录该小程序！',
      });
    }
  },
  submitClick1(){
    // this.checkRegister(this.data.orgCode,this.data.code).then(_=>{
    //   this.submitClick()
    // })

    // this.checkIdentity().then(_=>{
    //   this.checkRegister(this.data.orgCode,this.data.code).then(_=>{
    //     this.submitClick()
    //   })
    // })
    this.checkIdentity().then(_=>{
      console.log(this.data.type);
      if(this.data.type==0){
        this.submitClickType0()
      }
      if(this.data.type==1){
        this.submitClickType1()
      }
      
      
          
    })
  },
  checkIdentity(){
    Toast.loading({
      duration: 0,
      mask: true,
      message: '操作中...',
      forbidClick: true,
    });
    return new Promise((reslove,reject)=>{
      let identifycode=this.data.identifycode.trim().toUpperCase()
      if(identifycode.length==17){
        identifycode=identifycode+'X'
      }
      let params = {
        name:this.data.username.trim(),
        identity:identifycode,
      }
      request(apiList.checkByPerson,params).then(res =>{
        Toast.clear()
        reslove()
      }).catch(err => {
        Toast.clear()
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: err.message,
          mask:true
        });
      })
    })
  },
  newLogin1(params){
    Toast.loading({
      duration: 0,
      message: '登录中...',
      forbidClick: true,
    });
    let self = this;
    wx.request({
      url: `${ApiRootUrl}/index/newLogin`,
      method: 'POST',
      header: {
        'content-type': 'application/json; charset=utf-8',
        'cookie': wx.getStorageSync("sessionid")
      },
      data:params,
      success(res) {
        Toast.clear();
        if(res.data.code == 20000){
         wx.setStorageSync('userinfo', res.data.data)
        }else{
         
          Toast({
            duration: 3000,
            forbidClick: true,
            type: 'fail',
            message: res.data.message,
            mask:true
          });
        }
      },
      fail(res){
        Toast.clear();
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: '网络已断开',
        });
      }
    })
  },
  newLogin(params){
    Toast.loading({
      duration: 0,
      message: '登录中...',
      forbidClick: true,
    });
    let self = this;
    wx.request({
      url: `${ApiRootUrl}/index/newLogin`,
      method: 'POST',
      header: {
        'content-type': 'application/json; charset=utf-8',
        'cookie': wx.getStorageSync("sessionid")
      },
      data:params,
      success(res) {
        Toast.clear();
        if(res.data.code == 20000){
         wx.setStorageSync('userinfo', res.data.data)
          wx.redirectTo({
            url: `/pages/firstpage/firstpage?componentType=${self.data.type}&OrgCode=${self.data.code}&orgName=${self.data.name}&isLogin=${0}`,
          })
        }else{
         
          Toast({
            duration: 3000,
            forbidClick: true,
            type: 'fail',
            message: res.data.message,
            mask:true
          });
        }
      },
      fail(res){
        Toast.clear();
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: '网络已断开',
        });
      }
    })
  },
  // 提交确认
  submitClickType1() {
    let self = this;
    let flag = true;
    if (!this.data.canLogin) {
      Toast('请先阅读隐私协议');
      return;
    }
    if(!this.data.username){
      Toast('请输入正确姓名');
      return
    }
    if (!this.data.phone || !this.data.phone.length) {
      Toast('请输入手机号码！');
      return;
    }
    if (!this.data.identifycode || !this.data.identifycode.length) {
      Toast('请输入正确身份证号');
      return;
    }
    Toast.loading({
      duration: 0,
      mask: true,
      message: '操作中...',
      forbidClick: true,
    });
    let identifycode=this.data.identifycode.trim().toUpperCase()
      if(identifycode.length==17){
        identifycode=identifycode+'X'
      }
    let params = {
      name: this.data.username,
      phone: this.data.phone,
      identity: identifycode,
      componentType: this.data.type,
      name: this.data.username,
      descOrgCode:this.data.code,
      descComponentName:this.data.name,
      openId: wx.getStorageSync('openId')
    }
    console.log("params==>",params)
    wx.request({
      url: ApiRootUrl + '/index/newScanWaitRegister',
      header: {
        'content-type': 'application/json; charset=utf-8',
        'cookie': wx.getStorageSync("sessionid")
      },
      method: 'post',
      data: params,
      params: params,
      success(res) {
        Toast.clear();
        console.log("res==>",res)
        if (res.data.code == 20000) {
          console.log('res.data.data:', res.data.data);
self.newLogin(res.data.data)
          // wx.setStorageSync('userinfo', res.data.data)
          // wx.redirectTo({
          //   url: `../firstpage/firstpage?componentType=${self.data.type}&OrgCode=${self.data.code}&orgName=${self.data.name}&isLogin=${0}`,
          // })
        } else {
          Toast({
            duration: 3000,
            forbidClick: true,
            type: 'fail',
            message: res.data.message,
            mask:true
          });
         
            setTimeout(_=>{
               self.newCheckUser()
            },3000)
           
          
        }
      },
      fail(res) {
        console.log("res==>",res)
        Toast.clear();
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: '网络错误',
        });
      }
    })
  },
  submitClickType0() {
    let self = this;
    let flag = true;
    if (!this.data.canLogin) {
      Toast('请先阅读隐私协议');
      return;
    }
    if(!this.data.username){
      Toast('请输入正确姓名');
      return
    }
    if (!this.data.phone || !this.data.phone.length) {
      Toast('请输入手机号码！');
      return;
    }
    if (!this.data.identifycode || !this.data.identifycode.length) {
      Toast('请输入正确身份证号');
      return;
    }
    if (this.data.company == "请选择" ) {
      Toast('请选择面试企业！');
      return;
    }
    Toast.loading({
      duration: 0,
      mask: true,
      message: '操作中...',
      forbidClick: true,
    });
    let identifycode=this.data.identifycode.trim().toUpperCase()
      if(identifycode.length==17){
        identifycode=identifycode+'X'
      }
    let params = {
      name: this.data.username,
      phone: this.data.phone,
      identity: identifycode,
      componentType: this.data.type,
      name: this.data.username,
      originOrgCode:this.data.code,
      originComponentName: this.data.name,
      descOrgCode:this.data.orgCode,
      descComponentName:this.data.company,
      openId: wx.getStorageSync('openId')
    }
    console.log("params==>",params)
    wx.request({
      url: ApiRootUrl + '/index/newScanWaitRegister',
      header: {
        'content-type': 'application/json; charset=utf-8',
        'cookie': wx.getStorageSync("sessionid")
      },
      method: 'post',
      data: params,
      params: params,
      success(res) {
        Toast.clear();
        console.log("res==>",res)
        if (res.data.code == 20000) {
          console.log('res.data.data:', res.data.data);
self.newLogin(res.data.data)
          // wx.setStorageSync('userinfo', res.data.data)
          // wx.redirectTo({
          //   url: `../firstpage/firstpage?componentType=${self.data.type}&OrgCode=${self.data.code}&orgName=${self.data.name}&isLogin=${0}`,
          // })
        } else {
          Toast({
            duration: 3000,
            forbidClick: true,
            type: 'fail',
            message: res.data.message,
            mask:true
          });
          // if(res.data.message=='该员工在该企业已注册或者已注册过在职管理人员,无法继续注册!'){
            setTimeout(_=>{
               self.newCheckUser()
            },3000)
           
          // }
        }
      },
      fail(res) {
        console.log("res==>",res)
        Toast.clear();
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: '网络错误',
        });
      }
    })
  },
  submitClick() {
    let self = this;
    let flag = true;
    if (!this.data.canLogin) {
      Toast('请先阅读隐私协议');
      return;
    }
    if(!this.data.username){
      Toast('请输入正确姓名');
      return
    }
    if (!this.data.phone || !this.data.phone.length) {
      Toast('请输入手机号码！');
      return;
    }
    if (!this.data.identifycode || !this.data.identifycode.length) {
      Toast('请输入正确身份证号');
      return;
    }
    if(this.data.type == 0){
      if (this.data.company == "请选择" ) {
        Toast('请选择面试企业！');
        return;
      }
    }
    Toast.loading({
      duration: 0,
      mask: true,
      message: '操作中...',
      forbidClick: true,
    });
    let params = {
      name: this.data.username,
      phone: this.data.phone,
      identity: this.data.identifycode,
      componentType: this.data.type,
      name: this.data.username,
      originOrgCode:Number(this.data.type) == 0 ? this.data.code:"",
      originComponentName: Number(this.data.type) == 0 ?this.data.name:"",
      descOrgCode:Number(this.data.type) == 0 ? this.data.orgCode : this.data.code,
      descComponentName: Number(this.data.type) == 0 ?this.data.company : this.data.name,
      openId: wx.getStorageSync('openId')
    }
    console.log("params==>",params)
    wx.request({
      url: ApiRootUrl + '/index/registerEmployee',
      header: {
        'content-type': 'application/json; charset=utf-8',
        'cookie': wx.getStorageSync("sessionid")
      },
      method: 'post',
      data: params,
      params: params,
      success(res) {
        Toast.clear();
        console.log("res==>",res)
        if (res.data.code == 20000) {
          console.log('res.data.data:', res.data.data);
          wx.setStorageSync('userinfo', res.data.data)
          wx.redirectTo({
            url: `../firstpage/firstpage?componentType=${self.data.type}&OrgCode=${self.data.code}&orgName=${self.data.name}&isLogin=${0}`,
          })
        } else {
          Toast({
            duration: 3000,
            forbidClick: true,
            type: 'fail',
            message: res.data.message,
            mask:true
          });
        }
      },
      fail(res) {
        console.log("res==>",res)
        Toast.clear();
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: '网络错误',
        });
      }
    })
  },
  // 公司选择确认
  companyConfirm(event) {
    console.log(event)
    this.setData({
      showcompany: false,
      company: event.detail.value.text,
      orgCode: event.detail.value.id,
    })
  },
  //二维码的orgcode劳务工注册传labourCode 企业自招传componentCode

  checkRegister(componentCode,labourCode) {
    console.log(componentCode);
    Toast.loading({
      message: '加载中...',
      mask: true,
      duration: 0,
      forbidClick: true,
    });
    if(this.data.type==1){
      componentCode=labourCode;
      labourCode=''
    }
    let self = this;
    let openId = wx.getStorageSync("openId");
    return new Promise((reslove,reject)=>{
      let url = `${ApiRootUrl}/index/checkRegisterLabourWorker?openId=${openId}&labourCode=${labourCode}&componentCode=${componentCode}`;
    console.log("url======>",url)
    
    wx.request({
      url: url,
      method: 'GET',
      header: {
        'content-type': 'application/json; charset=utf-8',
        'cookie': wx.getStorageSync("sessionid")
      },
      success(res){
        Toast.clear();
        console.log("res====>",res)
        if (res.data.code == 20000) {
          wx.setStorageSync('userinfo', res.data.data)
          console.log("接口返回数据：", res.data.data)
          wx.showModal({
            title: '提示',
            content: '您已注册过心园通小程序,是否需要重新提交修改信息?',
            cancelText:"进入系统",
            confirmText:"重新注册",
            success (res) {
              if (res.confirm) {
                reslove()
              } else if (res.cancel) {
                wx.redirectTo({
                  url: `/pages/firstpage/firstpage?componentType=${self.data.type}&OrgCode=${self.data.code}&orgName=${self.data.name}&isLogin=${0}`,
                })
              }
            }
          })
          
          
        } else if (res.data.code == 30000) {
          reslove()
        } else if (res.data.code == 30002) {
          reslove()
        }else if (res.data.code == 30001) {
          self.setData({
          tishiShow:true,
          message:res.data.message
         })
        } else {
          Toast({
            duration: 3000,
            forbidClick: true,
            type: 'fail',
            message: res.data.message,
            mask:true
          });
        }
      },
      fail(res) {
        Toast.clear();
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: '网络已断开',
        });
      }
    })
    })
   
    
  },
  getUserName() {
    let self=this
    let openId = wx.getStorageSync("openId");
    let url = `${ApiRootUrl}/index/newReloadInfo?openId=${openId}`;
    // Toast.loading({
    //   message: '加载中...',
    //   mask: true,
    //   duration: 0,
    //   forbidClick: true,
    // });
    wx.showLoading({
      title: '加载中...',
    })
    wx.request({
      url: url,
      method: 'GET',
      header: {
        'content-type': 'application/json; charset=utf-8',
        'cookie': wx.getStorageSync("sessionid")
      },
      success(res){
        // Toast.clear();
        wx.hideLoading()
        console.log("res====>111111",res)
        if (res.data.code == 20000) {
          if(res.data.data){
            self.setData({
          username:res.data.data.name,
          identifycode:res.data.data.identity,
          editidentity:true,
          editusername:true
       })
          }
        } else {
    
        }
        // Toast.clear();
      },
      fail(res) {
        // Toast.clear();
        wx.hideLoading()
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: '网络已断开',
        });
      }
    })
  },
  newCheckUser() {
    let self = this;
    let openId = wx.getStorageSync("openId");
    let url = `${ApiRootUrl}/index/newCheckUser?openId=${openId}`;
    // Toast.loading({
    //   message: '加载中...',
    //   mask: true,
    //   duration: 0,
    //   forbidClick: true,
    // });
    wx.showLoading({
      title: '加载中...',
    })
    wx.request({
      url: url,
      method: 'GET',
      header: {
        'content-type': 'application/json; charset=utf-8',
        'cookie': wx.getStorageSync("sessionid")
      },
      success(res){
        // Toast.clear();
        wx.hideLoading()
        console.log("res====>111111",res)
        if (res.data.code == 20000) {
        console.log('注册过小程序',res.data.data);
        let userList=res.data.data
        userList.forEach((item)=>{
          if(item.userType==0){
            item.text='待面试-'+item.componentName
          }
          if(item.userType==1){
            item.text='在职务工人员-'+item.componentName
          }
          if(item.userType==2&&item.componentName){
            item.text='在职管理人员-'+item.componentName
          }
          if(item.userType==2&&!item.componentName){
            item.text=item.user.roleName
          }
          if(item.userType==3){
            item.text='离职务工人员-'+item.componentName
          }
          if(item.userType==4){
            item.text='游客'
          }
          if(item.userType==5){
            item.text='外协-'+item.componentName
          }
          if(item.userType==7){
            item.text='未入职申请务工人员-'+item.componentName
          }
        })
        wx.showModal({
          title: '提示',
          content: '您已注册过心园通小程序,是否重新注册?',
          cancelText:"选择角色",
          confirmText:"继续注册",
          success (res) {
            if (res.confirm) {
              reslove()
            } else if (res.cancel) {
              self.setData({
                userList:userList,
                showUserList:true
              })
            }
          }
        })
        } else if (res.data.code == 30000) {
          let phone = wx.getStorageSync('phoneNumber')
          if(phone){
            wx.redirectTo({
              url: `./register/register?componentType=${self.data.type}&OrgCode=${self.data.code}&orgName=${self.data.name}`,
            })
          }
          
          
        } else if (res.data.code == 30002) {
          let phone = wx.getStorageSync('phoneNumber')
          if(phone){
            wx.redirectTo({
              url: `./register/register?componentType=${self.data.type}&OrgCode=${self.data.code}&orgName=${self.data.name}`,
            })
          }
          
        }else if (res.data.code == 30001) {
          self.setData({
            tishiShow:true,
            message:res.data.message
         })
        } else {
          // Toast({
          //   duration: 3000,
          //   forbidClick: true,
          //   type: 'fail',
          //   message: res.data.message,
          // });
        }
        // Toast.clear();
      },
      fail(res) {
        // Toast.clear();
        wx.hideLoading()
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: '网络已断开',
        });
      }
    })
  },
  isCanbaoConfirm(e){
    let self=this
    console.log(e);
    this.newLogin1(e.detail.value)
    let data=e.detail.value
    if (!data.user) {
      wx.redirectTo({
        url: `/pages/firstpage/firstpage?componentType=${self.data.type}&OrgCode=${self.data.code}&orgName=${self.data.name}&isLogin=${0}`,
      })
    }else{
       // 有user表示是非劳务工
       if (data.user.typeCode == 'business') {
        wx.redirectTo({
          url: '/pages/companyfirstpage/companyfirstpage',
        })
      } else if (data.user.typeCode == 'labour') {
        wx.redirectTo({
          url: '/pages/laborcompany/firstpage/firstpage',
        })
      }
    }
  },
  isCanbaoCancel(){
    let self=this
    this.setData({
      showUserList:false
    })
    wx.showModal({
      title: '提示',
      content: '您已注册过心园通小程序,是否重新注册?',
      cancelText:"选择角色",
      confirmText:"继续注册",
      success (res) {
        if (res.confirm) {
          reslove()
        } else if (res.cancel) {
          self.setData({
            showUserList:true
          })
        }
      }
    })
  },
  closeUserList(){
    let self=this
    this.setData({
      showUserList:false
    })
    wx.showModal({
      title: '提示',
      content: '您已注册过心园通小程序,是否重新注册?',
      cancelText:"选择角色",
      confirmText:"继续注册",
      success (res) {
        if (res.confirm) {
          reslove()
        } else if (res.cancel) {
          self.setData({
            showUserList:true
          })
        }
      }
    })
  },
  companyClose() {
    this.setData({
      showcompany: false
    })
  },
  // 公司选择取消
  companyCancel() {
    this.setData({
      showcompany: false
    })
  },
  companyClick(event) {
    this.setData({
      showcompany: true
    })
    console.log(event)
  },
  toOpen(){
    this.timer && clearInterval(this.timer)
    
    this.timer = setInterval(() => {
      let count = this.data.count
      if(count <= 0){
        clearInterval(this.timer)
        this.setData({
          count:count
        })
      }else{
        this.setData({
          count:count - 1
        })
      }
    }, 1000);
    if(this.data.canLogin){
      this.setData({
        canLogin:false
      })
    }else{
      this.setData({
        show:true
      })
    }
  },
  onClose(){
    this.timer && clearInterval(this.timer)
    this.setData({
      show:false
    })
  },
  setPrativy(){
    this.setData({
      canLogin:true,
      show:false
    })
  },
  // 初始化公司list
  initCompany() {
    let self = this;
    let orgCode = this.data.code;
    console.log("orgCode==>",orgCode)
    wx.request({
      url: `${ApiRootUrl}/labor/queryBusinessList/${orgCode}`,
      method: 'get',
      header: {
        'content-type': 'application/json; charset=utf-8',
        'cookie': wx.getStorageSync("sessionid")
      },
      success(res) {
        if (res.data.code == 20000) {
          let columns = [];
          res.data.data.forEach((item) => {
            columns.push({
              id: item.orgCode,
              text: item.companyName
            })
          })
          app.globalData.companyList = columns;
          self.setData({
            columns: columns
          })
          console.log(res.data.data);
        } else {
          Toast({
            duration: 3000,
            forbidClick: true,
            type: 'fail',
            message: res.data.message,
            mask:true
          });
        }
      },
      fail(res) {
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: '网络错误',
        });
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('页面参数',options);
    let phone = wx.getStorageSync("phoneNumber");
    let code = options.OrgCode;
    let name = options.orgName;
    let type = options.componentType;
    if(type == "undefined"){
      type = 1
    }
    if(code == "undefined"){
      code = "lghx001"
    }
    if(name == "undefined"){
      name = "乐金化学"
    }
    this.setData({
      phone: phone,
      code: code,
      name: name,
      type:Number(type) 
    })
    this.initCompany();
    this.getUserName()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})